package org.summerframework.component.mybites.config;

import org.summerframework.component.mybites.redislock.LockUtil;
import org.summerframework.component.mybites.redislock.Locker;
import org.summerframework.component.mybites.redislock.RedissonLocker;
import org.summerframework.component.mybites.redislock.SynchronizedInterceptor;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;

/**
 * @author 石超
 * @version v1.0.0
 */
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@EnableConfigurationProperties(RedisProperties.class)
public class RedissonConfiguration {

    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort()).setPassword(redisProperties.getPassword()).setDatabase(redisProperties.getDatabase());
        return Redisson.create(config);
    }

    @Bean
    public Locker locker(RedissonClient redissonClient) {
        Locker locker = new RedissonLocker(redissonClient);
        //设置LockUtil的锁处理对象
        LockUtil.setLocker(locker);
        return locker;
    }

    @Bean
    public SynchronizedInterceptor synchronizedInterceptor() {
        return new SynchronizedInterceptor();
    }
}
